/**
 * 边工厂类
 * 负责创建和管理工作流边（连接线）
 */
class EdgeFactory {
  /**
   * 创建边实例
   * @param {Object} source - 源节点
   * @param {Object} target - 目标节点
   * @param {Object} data - 边数据
   * @param {Object} graph - X6图形实例
   * @returns {Object} 边实例
   */
  createEdge(source, target, data = {}, graph) {
    const edgeConfig = {
      shape: 'edge',
      source: { cell: source.id },
      target: { cell: target.id },
      data: {
        ...data,
        type: data.type || 'transition',
        code: data.code || `edge_${Date.now()}`
      },
      attrs: {
        line: {
          stroke: '#5F95FF',
          strokeWidth: 1,
          targetMarker: {
            name: 'classic',
            width: 12,
            height: 8
          }
        }
      },
      labels: data.name ? [
        {
          attrs: {
            label: {
              text: data.name
            }
          }
        }
      ] : [],
      zIndex: 0
    }

    return graph.createEdge(edgeConfig)
  }

  /**
   * 更新边数据
   * @param {Object} edge - 边实例
   * @param {Object} newData - 新数据
   */
  updateEdgeData(edge, newData) {
    const currentData = edge.getData() || {}
    edge.setData({ ...currentData, ...newData })
    
    // 更新标签
    if (newData.name) {
      edge.setLabels([
        {
          attrs: {
            label: {
              text: newData.name
            }
          }
        }
      ])
    }
  }

  /**
   * 验证边数据
   * @param {Object} edge - 边实例
   * @returns {Array} 验证错误信息
   */
  validateEdge(edge) {
    const errors = []
    const data = edge.getData() || {}
    
    // 检查必填字段
    if (!data.name || data.name.trim() === '') {
      errors.push('变迁名称是必填字段')
    }
    
    if (!data.code || data.code.trim() === '') {
      errors.push('变迁编码是必填字段')
    }

    return errors
  }

  /**
   * 获取边默认配置
   * @param {string} type - 边类型
   * @returns {Object} 默认配置
   */
  getDefaultConfig(type = 'transition') {
    return {
      name: '新建变迁',
      code: `${type}_${Date.now()}`,
      priority: 0,
      conditionClass: '',
      afterClass: ''
    }
  }
}

export const edgeFactory = new EdgeFactory()
